import { NRequireLabel } from "@/components/Uikit";
import { type TextareaProps, Textarea, useMantineTheme } from "@mantine/core";
import classNames from "classnames";
import React, { useState } from "react";
import { mergeClassNames } from "../tools";
import styles from "./Textarea.module.less";

interface ExtendedTextareaProps extends TextareaProps {
  textInputMaxLength?: number;
}
export const NTextarea = React.memo(
  ({
    className,
    onChange,
    textInputMaxLength,
    required,
    withAsterisk,
    label,
    error,
    ...restProps
  }: ExtendedTextareaProps) => {
    const [textInput, setTextInput] = useState<string>("");
    const [focus, setFocus] = useState<boolean>(false);
    const theme = useMantineTheme();
    {
      return (
        <div className={classNames("relative")}>
          {label ? (
            <NRequireLabel required={required} withAsterisk={withAsterisk} label={label} />
          ) : (
            ""
          )}
          <div
            className={classNames("relative bg-bgc-8 rounded-6")}
            style={{
              border: focus ? `1px solid ${theme.colors.borderColor[5]}` : `none`,
            }}
          >
            <Textarea
              className={classNames(className)}
              classNames={mergeClassNames(styles, restProps.classNames)}
              maxLength={textInputMaxLength}
              onChange={(event) => {
                setTextInput(event.currentTarget.value);
                onChange?.(event);
              }}
              {...restProps}
              onFocus={() => {
                setFocus(true);
              }}
              onBlur={() => {
                setFocus(false);
              }}
            />
            {textInputMaxLength ? (
              <div className={classNames(`absolute text-12 right-10 text-fcw-3 bottom-6`)}>
                {textInput.length}/{textInputMaxLength}
              </div>
            ) : null}
          </div>
          {error && <div className={`mt-4 flex items-center ${styles["error"]}`}>{error}</div>}
        </div>
      );
    }
  },
);
